const webpack = require('webpack');
const config = require('./webpack.config');
const SpritesmithPlugin = require('webpack-spritesmith');
const path = require('path');
const fs = require('fs');

const defaultParams = {
    src_cwd: path.resolve(__dirname, 'src/ico'),
    src_glob: '*.png',
    target_image: path.resolve(__dirname, 'dist/sprites/sprite.png'),
    target_css: path.resolve(__dirname, 'dist/sprites/sprite.less'),
    apiOptions_cssImageRef: '~sprite.png',
}

module.exports.entry = function (options, callback) {
    const _options = Object.assign({}, defaultParams, options);
    webpack({
        ...config, 
        plugins: [
            new SpritesmithPlugin({
                src: {
                    cwd: _options.src_cwd,
                    glob: _options.src_glob
                },
                target: {
                    image: _options.target_image,
                    css: _options.target_css
                },
                apiOptions: {
                    cssImageRef: _options.apiOptions_cssImageRef
                },
                // 雪碧图生成算法
                spritesmithOptions: {
                    padding: 4// 每个小图标之间的间隙
                }
            })
        ]
    }, (err, stats) => {
        // if(err || stats.hasErrors()){
        console.log(stats);
        if (err) {
            console.log(err,_options);
            console.log("构建过程出错！");
            callback(err);
        } else {
            console.log("构建成功！");
            callback(null,_options);
        }
    });
    // callback(null, options);
}